package com.newshub.ai.service.impl;

import com.newshub.ai.core.client.LLMClient;
import com.newshub.ai.core.factory.LLMClientFactory;
import com.newshub.ai.model.dto.ChatRequest;
import com.newshub.ai.model.dto.ChatResponse;

import com.newshub.ai.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;


import java.util.concurrent.CompletableFuture;

/**
 * 聊天服务实现类
 */
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private LLMClientFactory aiClientFactory;



    @Override
    public ChatResponse sendMessage(ChatRequest request) {
        try {
            log.info("收到同步聊天请求: {}", request.getMessage());

            // 创建LLM客户端
            LLMClient aiClient = aiClientFactory.createClient();
            
            if (!aiClient.isAvailable()) {
                log.error("LLM客户端不可用");
                return ChatResponse.error("LLM服务暂时不可用，请稍后重试");
            }

            // 发送消息到AI
            ChatResponse response = aiClient.chat(request);
            
            log.info("AI同步响应成功，模型: {}, 内容长度: {}", 
                response.getModel(), 
                response.getContent() != null ? response.getContent().length() : 0);

            return response;

        } catch (Exception e) {
            log.error("同步聊天服务异常", e);
            return ChatResponse.error("聊天服务异常: " + e.getMessage());
        }
    }





    @Override
    public String getServiceStatus() {
        try {
            LLMClient aiClient = aiClientFactory.createClient();
            boolean available = aiClient.isAvailable();
            String clientType = aiClient.getClientType();
            String modelInfo = aiClient.getModelInfo();
            
            return String.format("LLM服务状态: %s, 客户端类型: %s, 模型: %s", 
                available ? "正常" : "异常", 
                clientType, 
                modelInfo);
        } catch (Exception e) {
            log.error("获取服务状态异常", e);
            return "LLM服务状态: 异常 - " + e.getMessage();
        }
    }



    @Override
    public SseEmitter processStreamChat(ChatRequest request) {
        log.info("开始处理流式聊天请求: {}", request.getMessage());
        
        SseEmitter emitter = new SseEmitter(60000L); // 60秒超时
        
        // 设置SSE必要的响应头
        emitter.onCompletion(() -> log.info("SSE流完成"));
        emitter.onTimeout(() -> log.info("SSE流超时"));
        emitter.onError((ex) -> log.error("SSE流错误", ex));
        
        CompletableFuture.runAsync(() -> {
            try {
                // 创建AI客户端
                LLMClient aiClient = aiClientFactory.createClient();
                
                if (!aiClient.isAvailable()) {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI服务暂时不可用，请稍后重试"));
                    emitter.complete();
                    return;
                }
                
                // 发送开始事件
                emitter.send(SseEmitter.event()
                    .name("start")
                    .data("开始生成回复..."));
                
                // 调用流式聊天
                aiClient.chatStream(request, delta -> {
                    try {
                        emitter.send(SseEmitter.event()
                            .name("delta")
                            .data(delta));
                    } catch (IOException e) {
                        log.error("发送delta失败", e);
                    }
                });
                
                // 发送完成事件
                emitter.send(SseEmitter.event()
                    .name("done")
                    .data("生成完成"));
                emitter.complete();
                
            } catch (Exception e) {
                log.error("流式聊天异常", e);
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("聊天服务异常: " + e.getMessage()));
                    emitter.complete();
                } catch (IOException ex) {
                    log.error("发送错误事件失败", ex);
                }
            }
        });
        
        return emitter;
    }
}
